/* *****************************************************************************
 * JFab (http://code.google.com/p/jfab)
 * Copyright (c) 2011 JFab.org
 * Admin jfab@jeffreythompson.net
 *
 * See the file "LICENSE.txt" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 * *****************************************************************************/

package org.jfab.core.comparator;

import org.jfab.core.model.CGType;
import org.jfab.core.model.CGTypeUtilities;

/**
 * Provides a code generator field comparator.
 */
public class CGTypeComparator implements CGComparator<CGType>
{
    /** Serial version UID. */
    private static final long serialVersionUID = 1L;

    /** Code generator type utilities. */
    private final CGTypeUtilities _cgTypeUtils;

    /**
     * Construct this object with the given parameters.
     * 
     * @param cgTypeUtils Code generator type utilities. (required)
     */
    public CGTypeComparator(final CGTypeUtilities cgTypeUtils)
    {
        _cgTypeUtils = cgTypeUtils;
    }

    @Override
    public int compare(final CGType object1, final CGType object2)
    {
        int answer = -1;

        if (object1 == object2)
        {
            answer = 0;
        }
        else if (object1 == null)
        {
            answer = 1;
        }
        else if (object2 == null)
        {
            answer = -1;
        }
        else
        {
            final String name1 = _cgTypeUtils.toNameString(object1);
            final String name2 = _cgTypeUtils.toNameString(object2);

            if (name1 == name2)
            {
                answer = 0;
            }
            else if (name1 == null)
            {
                answer = 1;
            }
            else if (name2 == null)
            {
                answer = -1;
            }
            else
            {
                answer = name1.compareTo(name2);
            }
        }

        return answer;
    }
}
